﻿using System.Collections.Generic;
using System.Reflection;
using DesignByContract;
using FluentNHibernate;
using MadMediaManager.Core.ExtensionMethods;

namespace MadMediaManager.DataAccess
{
    public static class SessionSourceBuilder
    {
        public static ISessionSource Build(IDictionary<string, string> configurationProperties, string mappingAssembly)
        {
            Check.Require(!mappingAssembly.IsNullOrEmpty(), "mappingAssembly cannot be null");
            Check.Require(configurationProperties != null, "configurationProperties cannot be null");
            
            var persistenceModel = new PersistenceModel();
            persistenceModel
                .AddMappingsFromAssembly(Assembly.LoadFrom(MakeAssemblyLoadReady(mappingAssembly)));

            var source = new SessionSource(configurationProperties, persistenceModel);
            source.BuildSchema();
            return source;
        }

        private static string MakeAssemblyLoadReady(string assemblyName)
        {
            return assemblyName.EndsWith(".dll") ? assemblyName : assemblyName + ".dll";
        }
    }
}
